﻿using System;
using SneakyWeasel.Engine;
using System.Reflection;
using System.Diagnostics;
using System.IO;

namespace SneakyWeasel.Plugins
{
    [SWPluginAuthor("Sean Nall")]
    [SWPluginDescription("Turns the program into a self-monitoring and re-launching process.")]
    class SWSkynet : SWPlugin, ISWPlugin
    {
        [SWPluginParam("The number of processes to keep launched at all times.", 3)]
        public int NumProcs { get; set; }

        public override void OnPulse()
        {
            EnsureRunningProcesses();
        }

        private void EnsureRunningProcesses()
        {
            lock (this)
            {
                Process curr = Process.GetCurrentProcess();
                Process[] processes = Process.GetProcessesByName(curr.ProcessName);
                int num = processes.Length;

                Process[] vsProcs = Process.GetProcessesByName("weasel.vshost.exe"); // visual studio debug fix (didnt work)... in VS this will open a billion windows :(
                num += vsProcs.Length;

                if (NumProcs >= num)
                {
                    Assembly a = Assembly.GetExecutingAssembly();
                    Process pnew = new Process();
                    pnew.StartInfo.WorkingDirectory = Path.GetDirectoryName(a.Location);
                    pnew.StartInfo.FileName = Path.GetFileName(a.Location);
                    pnew.Start();
                    EnsureRunningProcesses();  // run it again
                }
            }
        }
    }
}
